<template>
  <div class="app-container">
    <!-- 页面标题和返回按钮 -->
    <div class="page-header">
      <h2 class="page-title">{{ pageTitle }}</h2>
    </div>

    <!-- 基本信息和时间范围选择 -->
    <el-card class="control-card" shadow="hover">
      <div slot="header" class="card-header">
        <span class="card-title">基本信息</span>
        <div class="header-controls">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            style="margin-right: 10px;">
          </el-date-picker>
          <el-button
            :type="compareEnabled ? 'success' : 'warning'"
            :icon="compareEnabled ? 'el-icon-check' : 'el-icon-s-data'"
            @click="toggleCompare"
            size="medium"
            :style="{ fontWeight: 'bold', fontSize: '14px' }"
          >
            {{ compareEnabled ? '已开启对比' : '开启数据对比' }}
          </el-button>
          <el-date-picker
            v-if="compareEnabled"
            v-model="compareDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="对比开始日期"
            end-placeholder="对比结束日期"
            value-format="yyyy-MM-dd"
            style="margin: 0 10px;"
          >
          </el-date-picker>
          <el-button type="primary" @click="refreshData">查询数据</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </div>
      </div>

      <el-row :gutter="20">
        <el-col :span="5">
          <div class="info-item">
            <label>渠道：</label>
            <span class="channel-tag"><dict-tag :options="dict.type.sys_channel" :value="basicInfo.channel"/></span>
          </div>
        </el-col>
        <el-col :span="5">
          <div class="info-item">
            <label>维度：</label>
            <span>{{ currentDimensionName }}</span>
          </div>
        </el-col>
        <el-col :span="5">
          <div class="info-item">
            <label>时间维度：</label>
            <el-select v-model="basicInfo.dataType" placeholder="时间维度" style="width: 100%;" >
              <el-option v-for="item in timeDimensionList" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
          </div>
        </el-col>
        <el-col :span="5">
          <div class="info-item">
            <label>应用：</label>
            <el-select v-model="basicInfo.pkg" placeholder="应用" style="width: 100%;"
              collapse-tags filterable clearable @change="handleAppChange">
              <el-option v-for="(item, index) in productList" :key="item + index" :label="item.name"
                :value="item.value" />
            </el-select>
          </div>
        </el-col>
        <el-col :span="5">
          <div class="info-item">
            <label>账户：</label>
            <el-select v-model="basicInfo.accountId" placeholder="账户" style="width: 100%;"
              :filter-method="accountFilter" filterable clearable @change="handleAccountChange">
              <el-option v-for="(item, index) in accountOptions" :key="item.dimensionId"
                :label="item.dimensionName" :value="item.dimensionId" />
            </el-select>
          </div>
        </el-col>
        <el-col :span="5">
          <div class="info-item">
            <label>单元：</label>
            <el-select v-model="basicInfo.unitId" placeholder="单元" style="width: 100%;"
              :filter-method="unitFilter" filterable clearable @change="handleUnitChange">
              <el-option v-for="(item, index) in unitOptions" :key="item.dimensionId"
                :label="item.dimensionName" :value="item.dimensionId" />
            </el-select>
          </div>
        </el-col>
        <el-col :span="5" v-if="showConvertCostMetric">
          <div class="info-item">
            <label>转化目标：</label>
            <span>{{ getConvertTarget() }}</span>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 图表区域 -->
    <el-card class="chart-card" shadow="hover" v-loading="chartLoading">
      <div slot="header" class="card-header">
        <span class="card-title">{{ getChartTitle() }}</span>
        <div class="chart-controls">
          <div class="metric-selection">
            <el-checkbox-group v-model="selectedMetrics" @change="updateChart">
              <el-checkbox label="cost">消耗</el-checkbox>
              <el-checkbox label="income">回收</el-checkbox>
              <el-checkbox label="roi">ROI</el-checkbox>
              <el-checkbox label="firstRoi">首日ROI</el-checkbox>
              <el-checkbox label="convertCost" v-if="showConvertCostMetric">转换成本</el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </div>
      <div id="trendChart" style="width: 100%; height: 400px;"></div>
    </el-card>

    <!-- 数据列表 -->
    <el-card class="table-card" shadow="hover">
      <div slot="header" class="card-header">
        <span class="card-title">数据列表</span>
      </div>

      <el-table
        v-loading="tableLoading"
        :data="tableData"
        :default-sort="defaultSort"
        style="width: 100%">

        <el-table-column label="日期" prop="acdate" min-width="1" align="center" v-if="basicInfo.dataType !== '1'">
          <template slot-scope="scope">
            <div v-if="compareEnabled && compareTableData && compareTableData.length">
              <div style="font-weight: 500; margin-bottom: 4px;">
                {{ formatAcdate(scope.row.acdate) }}
              </div>
              <div v-if="getCompareRowByIndex(scope.$index)" style="color: #6b7280; font-size: 12px; padding-top: 4px; border-top: 1px dashed #e5e7eb;">
                {{ formatAcdate(getCompareRowByIndex(scope.$index).acdate) }}
              </div>
            </div>
            <div v-else>
              {{ formatAcdate(scope.row.acdate) }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="日期" prop="acdate" min-width="1" align="center" v-if="basicInfo.dataType === '1'">
          <template slot-scope="scope">
            <div v-if="compareEnabled && compareTableData && compareTableData.length">
              <div style="font-weight: 500; margin-bottom: 4px;">
                {{ formatAcdate(scope.row.acdate) }}
              </div>
              <div v-if="getCompareRowByIndex(scope.$index)" style="color: #6b7280; font-size: 12px; padding-top: 4px; border-top: 1px dashed #e5e7eb;">
                {{ formatAcdate(getCompareRowByIndex(scope.$index).acdate) }}
              </div>
            </div>
            <div v-else>
              {{ formatAcdate(scope.row.acdate) }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="时间" prop="hr" min-width="1" align="center" v-if="basicInfo.dataType === '1'">
          <template slot-scope="scope">
            <div v-if="compareEnabled && compareTableData && compareTableData.length">
              <div style="font-weight: 500; margin-bottom: 4px;">
                {{ (scope.row.hr || '00') + ':00' }}
              </div>
              <div v-if="getCompareRowByIndex(scope.$index)" style="color: #6b7280; font-size: 12px; padding-top: 4px; border-top: 1px dashed #e5e7eb;">
                {{ (getCompareRowByIndex(scope.$index).hr || '00') + ':00' }}
              </div>
            </div>
            <div v-else>
              {{ (scope.row.hr || '00') + ':00' }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="消耗" prop="cost" min-width="2" align="center">
          <template slot-scope="scope">
            <div v-if="compareEnabled && compareTableData && compareTableData.length">
              <div>
                账面 当前: {{ scope.row.cost || 0 }}
                <span v-if="getCompareRowByIndex(scope.$index)" style="margin-left: 6px;">
                  对比: {{ getCompareMetricValue(scope.$index, 'cost') }}
                </span>
                <span
                  v-if="getCompareRowByIndex(scope.$index)"
                  :style="{
                    marginLeft: '6px',
                    color: getDiffColor(scope.row.cost || 0, getCompareMetricValue(scope.$index, 'cost')),
                    'font-weight': 'bold'
                  }"
                >
                  {{ getDiffText(scope.row.cost || 0, getCompareMetricValue(scope.$index, 'cost')) }}
                </span>
              </div>
              <div style="color: #909399; font-size: 12px; margin-top: 4px;">
                现金 当前: {{ scope.row.cashCost || 0 }}
                <span v-if="getCompareRowByIndex(scope.$index)">
                  ，对比: {{ getCompareRowByIndex(scope.$index).cashCost || 0 }}
                </span>
                <span
                  v-if="getCompareRowByIndex(scope.$index)"
                  :style="{
                    marginLeft: '6px',
                    color: getDiffColor(scope.row.cashCost || 0, getCompareRowByIndex(scope.$index).cashCost || 0),
                    'font-weight': 'bold'
                  }"
                >
                  {{ getDiffText(scope.row.cashCost || 0, getCompareRowByIndex(scope.$index).cashCost || 0) }}
                </span>
              </div>
            </div>
            <div v-else>
              <div>账面: {{ scope.row.cost || 0 }}</div>
              <div style="color: #909399; font-size: 12px;">现金: {{ scope.row.cashCost || 0 }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="回收" prop="income" min-width="2" align="center">
          <template slot-scope="scope">
            <div v-if="compareEnabled && compareTableData && compareTableData.length">
              <div>
                归因 当前: {{ scope.row.income || 0 }}
                <span v-if="getCompareRowByIndex(scope.$index)" style="margin-left: 6px;">
                  对比: {{ getCompareMetricValue(scope.$index, 'income') }}
                </span>
                <span
                  v-if="getCompareRowByIndex(scope.$index)"
                  :style="{
                    marginLeft: '6px',
                    color: getDiffColor(scope.row.income || 0, getCompareMetricValue(scope.$index, 'income')),
                    'font-weight': 'bold'
                  }"
                >
                  {{ getDiffText(scope.row.income || 0, getCompareMetricValue(scope.$index, 'income')) }}
                </span>
              </div>
              <div style="color: #909399; font-size: 12px; margin-top: 4px;">
                首日 当前: {{ getFirstIncome(scope.row) }}
                <span v-if="getCompareRowByIndex(scope.$index)">，对比: {{ getCompareMetricValue(scope.$index, 'firstIncome') }}</span>
                <span
                  v-if="getCompareRowByIndex(scope.$index)"
                  :style="{
                    marginLeft: '6px',
                    color: getDiffColor(getFirstIncome(scope.row), getCompareMetricValue(scope.$index, 'firstIncome')),
                    'font-weight': 'bold'
                  }"
                >
                  {{ getDiffText(getFirstIncome(scope.row), getCompareMetricValue(scope.$index, 'firstIncome')) }}
                </span>
              </div>
            </div>
            <div v-else>
              <div>归因: {{ scope.row.income || 0 }}</div>
              <div style="color: #909399; font-size: 12px;">首日: {{ getFirstIncome(scope.row) }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="ROI" prop="roi" min-width="2" align="center">
          <template slot-scope="scope">
            <div v-if="compareEnabled && compareTableData && compareTableData.length">
              <div>
                账面 当前: {{ scope.row.roi || 0 }}
                <span v-if="getCompareRowByIndex(scope.$index)" style="margin-left: 6px;">
                  对比: {{ getCompareMetricValue(scope.$index, 'roi') }}
                </span>
                <span
                  v-if="getCompareRowByIndex(scope.$index)"
                  :style="{
                    marginLeft: '6px',
                    color: getDiffColor(scope.row.roi || 0, getCompareMetricValue(scope.$index, 'roi')),
                    'font-weight': 'bold'
                  }"
                >
                  {{ getDiffText(scope.row.roi || 0, getCompareMetricValue(scope.$index, 'roi')) }}
                </span>
              </div>
              <div style="color: #909399; font-size: 12px; margin-top: 4px;">
                首日 当前: {{ getFirstIncomeRoi(scope.row) }}
                <span v-if="getCompareRowByIndex(scope.$index)">，对比: {{ getCompareMetricValue(scope.$index, 'firstRoi') }}</span>
                <span
                  v-if="getCompareRowByIndex(scope.$index)"
                  :style="{
                    marginLeft: '6px',
                    color: getDiffColor(getFirstIncomeRoi(scope.row), getCompareMetricValue(scope.$index, 'firstRoi')),
                    'font-weight': 'bold'
                  }"
                >
                  {{ getDiffText(getFirstIncomeRoi(scope.row), getCompareMetricValue(scope.$index, 'firstRoi')) }}
                </span>
              </div>
            </div>
            <div v-else>
              <div>账面: {{ scope.row.roi || 0 }}</div>
              <div style="color: #909399; font-size: 12px;">首日: {{ getFirstIncomeRoi(scope.row) }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="转换成本" prop="convertCost" min-width="2" align="center" v-if="showConvertCostMetric">
          <template slot-scope="scope">
            <div v-if="compareEnabled && compareTableData && compareTableData.length">
              <div>
                当前: {{ getConvertCost(scope.row) }}
                <span v-if="getCompareRowByIndex(scope.$index)" style="margin-left: 6px;">
                  对比: {{ getCompareMetricValue(scope.$index, 'convertCost') }}
                </span>
                <span
                  v-if="getCompareRowByIndex(scope.$index)"
                  :style="{
                    marginLeft: '6px',
                    color: getDiffColor(getConvertCost(scope.row), getCompareMetricValue(scope.$index, 'convertCost')),
                    'font-weight': 'bold'
                  }"
                >
                  {{ getDiffText(getConvertCost(scope.row), getCompareMetricValue(scope.$index, 'convertCost')) }}
                </span>
              </div>
            </div>
            <div v-else>
              {{ getConvertCost(scope.row) }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="利润" prop="profit" min-width="2" align="center">
          <template slot-scope="scope">
            <div v-if="compareEnabled && compareTableData && compareTableData.length">
              <div>
                当前: {{ getProfit(scope.row) }}
                <span v-if="getCompareRowByIndex(scope.$index)" style="margin-left: 6px;">
                  对比: {{ getCompareMetricValue(scope.$index, 'profit') }}
                </span>
                <span
                  v-if="getCompareRowByIndex(scope.$index)"
                  :style="{
                    marginLeft: '6px',
                    color: getDiffColor(getProfit(scope.row), getCompareMetricValue(scope.$index, 'profit')),
                    'font-weight': 'bold'
                  }"
                >
                  {{ getDiffText(getProfit(scope.row), getCompareMetricValue(scope.$index, 'profit')) }}
                </span>
              </div>
            </div>
            <div v-else>
              {{ getProfit(scope.row) }}
            </div>
          </template>
        </el-table-column>

        <!-- <el-table-column label="更新时间" prop="updatetime" min-width="1" align="center"/> -->
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { dataList, getPlaceList } from "@/api/place-report/gdtSearch";
import { getAllAppList } from "@/api/common/index-adv";
import { getAccountList } from "@/api/place-manage/account";
import { arrParamToStr, formatTime, computedDate } from '@/utils/index';
import echarts from 'echarts';

export default {
  name: 'GdtSearchDataDetails',
  dicts: ['sys_channel'],
  data() {
    return {
      chartLoading: false,
      tableLoading: false,
      basicInfo: {},
      pageTitle: '数据详情',
      dateRange: [],
      compareEnabled: false,
      compareDateRange: [],
      selectedMetrics: ['cost','income','roi','firstRoi'], // 改为数组，默认选中消耗
      chart: null,
      chartData: [],
      compareChartData: [],
      tableData: [],
      compareTableData: [],
      total: 0,
      defaultSort: { prop: 'acdate,hr', order: 'descending' },
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: 'acdate,hr',
        isAsc: 'desc'
      },
      // 应用列表
      productList: [],
      // 账户列表
      accountList: [],
      accountOptions: [],
      // 单元列表
      unitList: [],
      unitOptions: [],
      // 数据维度
      dataDimensionList: [
        { name: '应用', value: '2' },
        { name: '账户', value: '3' },
        { name: '单元', value: '5' }
      ],
      // 时间维度
      timeDimensionList: [
        { name: '天', value: '0' },
        { name: '小时', value: '1' }
      ],
      // 指标配置 - 优化颜色方案和视觉效果
      metricConfig: {
        cost: {
          name: '消耗',
          color: '#1E40AF', // 深蓝色，更高对比度
          lightColor: 'rgba(30, 64, 175, 0.1)', // 浅色用于面积图
          unit: '元',
          yAxisIndex: 0,
          type: 'amount',
          symbol: 'circle' // 数据点形状
        },
        income: {
          name: '回收',
          color: '#059669', // 深绿色，更鲜明
          lightColor: 'rgba(5, 150, 105, 0.1)',
          unit: '元',
          yAxisIndex: 0,
          type: 'amount',
          symbol: 'circle' // 方形数据点
        },
        roi: {
          name: 'ROI',
          color: '#DC2626', // 深红色，高对比度
          lightColor: 'rgba(220, 38, 38, 0.1)',
          unit: '',
          yAxisIndex: 1,
          type: 'ratio',
          symbol: 'circle' // 菱形数据点
        },
        firstRoi: {
          name: '首日ROI',
          color: '#7C3AED', // 紫色，独特识别
          lightColor: 'rgba(124, 58, 237, 0.1)',
          unit: '',
          yAxisIndex: 1,
          type: 'ratio',
          symbol: 'circle' // 三角形数据点
        },
        convertCost: {
          name: '转换成本',
          color: '#F59E0B', // 橙色，区别于其他指标
          lightColor: 'rgba(245, 158, 11, 0.1)',
          unit: '元',
          yAxisIndex: 0,
          type: 'amount',
          symbol: 'circle' // 圆形数据点
        }
      }
    }
  },
  computed: {
    // 动态计算当前维度
    currentDimension() {
      // 根据选中的最小维度确定当前维度(GDT没有计划维度)
      if (this.basicInfo.unitId) {
        return { name: '单元', value: '5' };
      } else if (this.basicInfo.accountId) {
        return { name: '账户', value: '3' };
      } else {
        return { name: '应用', value: '2' };
      }
    },
    // 当前维度名称
    currentDimensionName() {
      return this.currentDimension.name;
    },
    // 当前维度值（用于API调用）
    currentDimensionValue() {
      return this.currentDimension.value;
    },
    // 判断是否显示转换成本指标（根据是否选择了单元）
    showConvertCostMetric() {
      return !!this.basicInfo.unitId;
    }
  },
  created() {
    this.initBasicInfo();
    this.initDateRange();
    this.getProductList();
    this.loadData();
  },
  mounted() {
    this.initChart();
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
    }
  },
  methods: {
    // 获取应用列表
    getProductList() {
      getAllAppList().then(response => {
        this.productList = response.data.map(item => {
          return {
            id: item.id,
            appcode: item.appcode,
            name: item.appname,
            value: item.apppkg
          }
        })
      })
    },

    // 获取账户/计划/广告组列表
    getPlaceList(type, params = {}) {
      const requestParams = { type: type, ...params };
      getPlaceList(requestParams).then(response => {
        if(type == 3){
          this.accountList = response.data;
          this.accountOptions = response.data;
        } else if(type == 5){
          this.unitList = response.data;
          this.unitOptions = response.data;
        }
      })
    },

    // 账户过滤
    accountFilter(query) {
      if (!query) {
        this.accountOptions = this.accountList;
        return;
      }
      const keyword = query.toLowerCase();
      this.accountOptions = this.accountList.filter(item =>
        item.dimensionId.toLowerCase().includes(keyword) ||
        item.dimensionName.toLowerCase().includes(keyword)
      );
    },

    // 单元过滤
    unitFilter(query) {
      if (!query) {
        this.unitOptions = this.unitList;
        return;
      }
      const keyword = query.toLowerCase();
      this.unitOptions = this.unitList.filter(item =>
        item.dimensionId.toLowerCase().includes(keyword) ||
        item.dimensionName.toLowerCase().includes(keyword)
      );
    },

    // 应用变化处理
    handleAppChange(value) {
      // 更新应用名称
      const selectedApp = this.productList.find(item => item.value === value);
      if (selectedApp) {
        this.basicInfo.appName = selectedApp.name;
      }

      // 清空下级选择
      this.basicInfo.accountId = '';
      this.basicInfo.accountName = '';
      this.basicInfo.unitId = '';
      this.basicInfo.unitName = '';

      // 重新获取下级数据
      if (value) {
        this.getPlaceList(3, { pkg: value }); // 获取账户列表
        this.getPlaceList(5, { pkg: value }); // 获取单元列表
      }
    },

    // 账户变化处理
    handleAccountChange(value) {
      // 更新账户名称
      const selectedAccount = this.accountList.find(item => item.dimensionId === value);
      if (selectedAccount) {
        this.basicInfo.accountName = selectedAccount.dimensionName;
      }

      // 清空下级选择
      this.basicInfo.unitId = '';
      this.basicInfo.unitName = '';

      // 重新获取下级数据
      if (value && this.basicInfo.pkg) {
        const params = { pkg: this.basicInfo.pkg, accountId: value };
        this.getPlaceList(5, params); // 获取单元列表
      }
    },

    // 单元变化处理
    handleUnitChange(value) {
      // 更新单元名称
      const selectedUnit = this.unitList.find(item => item.dimensionId === value);
      if (selectedUnit) {
        this.basicInfo.unitName = selectedUnit.dimensionName;
      }

      // 根据是否选择单元，自动添加或移除转换成本指标
      if (value) {
        // 选择了单元，添加转换成本指标
        if (!this.selectedMetrics.includes('convertCost')) {
          this.selectedMetrics.push('convertCost');
        }
      } else {
        // 清空了单元，移除转换成本指标
        const index = this.selectedMetrics.indexOf('convertCost');
        if (index > -1) {
          this.selectedMetrics.splice(index, 1);
        }
      }
    },

    // 初始化基本信息
    initBasicInfo() {
      this.basicInfo = {
        pkg: this.$route.query.pkg || '',
        appName: this.$route.query.appName || '',
        channel: this.$route.query.channel || '',
        type: this.$route.query.type || '3', // 保留type字段用于兼容
        dataType: this.$route.query.dataType || '0', // 时间维度类型 (0:天, 1:小时)
        beginDate: this.$route.query.beginDate || '',
        endDate: this.$route.query.endDate || '',
        accountId: this.$route.query.accountId || '',
        accountName: this.$route.query.accountName || '',
        unitId: this.$route.query.unitId || '',
        unitName: this.$route.query.unitName || ''
      };

      // 根据实际选中的ID推断正确的type值(GDT没有计划维度)
      if (this.basicInfo.unitId) {
        this.basicInfo.type = '5';
      } else if (this.basicInfo.accountId) {
        this.basicInfo.type = '3';
      } else {
        this.basicInfo.type = '2';
      }

      // 如果选择了单元，默认添加转换成本指标
      if(this.basicInfo.unitId && !this.selectedMetrics.includes('convertCost')){
        this.selectedMetrics.push('convertCost');
      }
       const params = {
        pkg: this.basicInfo.pkg
      };
      if(this.basicInfo.accountId){
        params.accountId = this.basicInfo.accountId;
      }
      if(this.basicInfo.unitId){
        params.unitId = this.basicInfo.unitId;
      }
      const currentType = this.currentDimensionValue;
      if(currentType){
        if(currentType == '2'){
            this.getPlaceList('3',params);
        }
        if(currentType == '3'){
            this.getPlaceList('3',params);
            this.getPlaceList('5',params);
        }
        if(currentType == '5'){
            this.getPlaceList('3',params);
            this.getPlaceList('5',params);
        }
      }
    },

    // 初始化日期范围
    initDateRange() {
      if (this.basicInfo.dataType === '1') {
        // 小时维度：使用从主页面传递过来的日期范围
        if (this.basicInfo.beginDate && this.basicInfo.endDate) {
          // 将8位数字格式转换为带连字符的格式
          const startDate = this.formatDateString(this.basicInfo.beginDate);
          const endDate = this.formatDateString(this.basicInfo.endDate);
          this.dateRange = [startDate, endDate];
        } else {
          // 如果没有传入日期参数，小时维度默认显示7天数据
          const endDate = computedDate(new Date());
          const startDate = computedDate(new Date());;
          this.dateRange = [startDate, endDate];
        }
      } else {
        // 天维度：始终查询最近30天的数据，忽略传入的日期参数
        const endDate = this.formatDateString(computedDate(new Date()));
        const startDate = this.formatDateString(this.getDateBefore(endDate, 30));
        this.dateRange = [startDate, endDate];
      }
    },

    // 获取指定日期前N天的日期
    getDateBefore(dateStr, days) {
      const date = new Date(dateStr.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3'));
      date.setDate(date.getDate() - days);
      return date.toISOString().slice(0, 10).replace(/-/g, '');
    },

    // 格式化日期字符串：将8位数字格式转换为带连字符的格式
    formatDateString(dateStr) {
      if (!dateStr) return '';
      // 如果已经是带连字符的格式，直接返回
      if (dateStr.includes('-')) return dateStr;
      // 将8位数字格式（如 "20231201"）转换为带连字符的格式（如 "2023-12-01"）
      if (dateStr.length === 8) {
        return `${dateStr.slice(0, 4)}-${dateStr.slice(4, 6)}-${dateStr.slice(6, 8)}`;
      }
      return dateStr;
    },

    // 计算日期范围的天数（包含起止）
    getRangeDays(range) {
      if (!range || range.length !== 2 || !range[0] || !range[1]) return 0;
      const start = new Date(range[0]);
      const end = new Date(range[1]);
      const diff = (end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24);
      return diff >= 0 ? diff + 1 : 0;
    },

    // 校验对比日期范围与主日期范围天数是否一致
    validateCompareRange() {
      if (!this.compareEnabled) return true;
      if (!this.compareDateRange || this.compareDateRange.length !== 2) {
        this.$modal.msgWarning('请选择对比时间范围');
        return false;
      }
      const baseDays = this.getRangeDays(this.dateRange);
      const compareDays = this.getRangeDays(this.compareDateRange);
      if (baseDays !== compareDays) {
        this.$modal.msgWarning(`对比时间范围的天数必须与原时间范围一致（当前${baseDays}天，对比${compareDays}天）`);
        return false;
      }
      return true;
    },

    // 获取时间维度名称
    getTimeDimensionName(dataType) {
      const timeDimensionMap = {
        '0': '天',
        '1': '小时'
      };
      return timeDimensionMap[dataType] || '天';
    },

    // 获取转化目标
    getConvertTarget() {
      // 从图表数据中获取第一条记录的convertTypes
      if (this.chartData && this.chartData.length > 0) {
        const convertTypes = this.chartData[0].convertTypes;
        return convertTypes || '未设置';
      }
      return '未设置';
    },

    // 刷新数据
    refreshData() {
      if (!this.dateRange || this.dateRange.length !== 2) {
        this.$modal.msgWarning('请选择时间范围');
        return;
      }
      if (!this.validateCompareRange()) {
        return;
      }
      this.loadData();
    },

    // 切换对比模式
    toggleCompare() {
      this.compareEnabled = !this.compareEnabled;
      if (!this.compareEnabled) {
        this.compareDateRange = [];
        this.compareChartData = [];
        this.compareTableData = [];
        this.updateChart();
      } else {
        // 开启对比模式时，自动设置日期范围
        const today = new Date();
        const yesterday = new Date(today);
        yesterday.setDate(yesterday.getDate() - 1);

        // 格式化日期为 yyyy-MM-dd
        const formatDate = (date) => {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          return `${year}-${month}-${day}`;
        };

        const todayStr = formatDate(today);
        const yesterdayStr = formatDate(yesterday);

        // 设置当前查询时间为今天
        this.dateRange = [todayStr, todayStr];

        // 设置对比时间为昨天
        this.compareDateRange = [yesterdayStr, yesterdayStr];
      }
    },

    resetQuery() {
      this.compareEnabled = false;
      this.compareDateRange = [];
      this.compareChartData = [];
      this.compareTableData = [];
      this.initDateRange();
      this.loadData();
    },

    // 加载数据
    loadData() {
      this.chartLoading = true;
      this.tableLoading = true;

      const baseParams = this.buildQueryParams(this.dateRange);
      baseParams.dataType = this.basicInfo.dataType;
      baseParams.orderByColumn = 'acdate,hr';
      baseParams.isAsc = 'descending';

      const mainRequest = dataList(arrParamToStr(baseParams));

      let compareRequest = null;
      if (this.compareEnabled) {
        const compareParams = this.buildQueryParams(this.compareDateRange);
        compareParams.dataType = this.basicInfo.dataType;
        compareParams.orderByColumn = 'acdate,hr';
        compareParams.isAsc = 'descending';
        compareRequest = dataList(arrParamToStr(compareParams));
      }

      const handleMainResponse = (response) => {
        // 解析数据
        let chartData = response.rows.map(item => ({
          ...item,
          arpuData: item.arpuData ? JSON.parse(item.arpuData) : null,
          convertData: item.convertData ? JSON.parse(item.convertData) : null,
          behaviorData: item.behaviorData ? JSON.parse(item.behaviorData) : null
        }));

        let tableData = response.rows.map(item => ({
          ...item,
          updatetime: formatTime(item.updatetime),
          arpuData: item.arpuData ? JSON.parse(item.arpuData) : null
        }));

        // 小时维度：图表数据升序，表格数据降序
        if (this.basicInfo.dataType === '1') {
          const sortByDateTimeAsc = (a, b) => {
            if (a.acdate !== b.acdate) return a.acdate - b.acdate;
            return (a.hr || 0) - (b.hr || 0);
          };
          const sortByDateTimeDesc = (a, b) => {
            if (a.acdate !== b.acdate) return b.acdate - a.acdate;
            return (b.hr || 0) - (a.hr || 0);
          };
          chartData.sort(sortByDateTimeAsc);
          tableData.sort(sortByDateTimeDesc);
        } else {
          // 天维度：图表数据升序，表格数据降序
          const sortByDateAsc = (a, b) => a.acdate - b.acdate;
          const sortByDateDesc = (a, b) => b.acdate - a.acdate;
          chartData.sort(sortByDateAsc);
          tableData.sort(sortByDateDesc);
        }

        this.chartData = chartData;
        this.tableData = tableData;
        this.total = response.total;
      };

      if (!compareRequest) {
        mainRequest.then(response => {
          handleMainResponse(response);
          this.compareChartData = [];
          this.compareTableData = [];
          this.updateChart();
        }).catch(error => {
          this.$modal.msgError('加载图表数据失败');
        }).finally(() => {
          this.chartLoading = false;
          this.tableLoading = false;
        });
      } else {
        Promise.all([mainRequest, compareRequest]).then(([mainRes, compareRes]) => {
          handleMainResponse(mainRes);

          // 解析对比数据
          let compareChartData = compareRes.rows.map(item => ({
            ...item,
            arpuData: item.arpuData ? JSON.parse(item.arpuData) : null,
            convertData: item.convertData ? JSON.parse(item.convertData) : null,
            behaviorData: item.behaviorData ? JSON.parse(item.behaviorData) : null
          }));

          let compareTableData = compareRes.rows.map(item => ({
            ...item,
            updatetime: formatTime(item.updatetime),
            arpuData: item.arpuData ? JSON.parse(item.arpuData) : null
          }));

          // 小时维度：图表数据升序，表格数据降序
          if (this.basicInfo.dataType === '1') {
            const sortByDateTimeAsc = (a, b) => {
              if (a.acdate !== b.acdate) return a.acdate - b.acdate;
              return (a.hr || 0) - (b.hr || 0);
            };
            const sortByDateTimeDesc = (a, b) => {
              if (a.acdate !== b.acdate) return b.acdate - a.acdate;
              return (b.hr || 0) - (a.hr || 0);
            };
            compareChartData.sort(sortByDateTimeAsc);
            compareTableData.sort(sortByDateTimeDesc);
          }

          this.compareChartData = compareChartData;
          this.compareTableData = compareTableData;

          this.updateChart();
        }).catch(error => {
          this.$modal.msgError('加载图表数据失败');
        }).finally(() => {
          this.chartLoading = false;
          this.tableLoading = false;
        });
      }
    },

    // 构建查询参数
    buildQueryParams(range) {
      const dateRange = range && range.length === 2 ? range : this.dateRange;
      const currentType = this.currentDimensionValue; // 使用动态计算的维度值
      const queryParams = {
        type: currentType,
        pkg: this.basicInfo.pkg,
        channel: this.basicInfo.channel,
        pageNum: 1,
        pageSize: 100,
        beginDate: dateRange[0].replace(/-/g, ''),
        endDate: dateRange[1].replace(/-/g, '')
      };

      // 根据维度添加对应的ID参数(GDT没有计划维度)
      if (currentType === '3') {
        queryParams.accountId = [this.basicInfo.accountId];
      } else if (currentType === '5') {
        queryParams.accountId = [this.basicInfo.accountId];
        queryParams.unitId = [this.basicInfo.unitId];
      }

      return queryParams;
    },

    // 初始化图表
    initChart() {
      this.$nextTick(() => {
        const chartDom = document.getElementById('trendChart');
        if (chartDom) {
          this.chart = echarts.init(chartDom);
          window.addEventListener('resize', () => {
            if (this.chart) {
              this.chart.resize();
            }
          });
        }
      });
    },

    // 更新图表 - 支持双Y轴多指标显示
    updateChart() {
      if (!this.chart || !this.chartData.length) return;

      // 如果没有选中任何指标，完全清空图表
      if (!this.selectedMetrics || this.selectedMetrics.length === 0) {
        const emptyOption = {
          title: {
            text: '请选择要显示的指标',
            left: 'center',
            textStyle: {
              color: '#999',
              fontSize: 16
            }
          },
          tooltip: {},
          legend: { show: false },
          xAxis: {
            show: false,
            type: 'category',
            data: []
          },
          yAxis: [
            { show: false, type: 'value' },
            { show: false, type: 'value' }
          ],
          series: []
        };
        this.chart.setOption(emptyOption, true); // 使用notMerge=true完全替换配置
        return;
      }

      // 根据时间维度生成不同的时间标签（原始日期，用于数据对齐）
      const dates = this.basicInfo.dataType === '1'
        ? [...new Set(this.chartData.map(item => `${item.acdate}-${String(item.hr || 0).padStart(2, '0')}`))]
            .sort((a, b) => {
              const [dateA, hourA] = a.split('-');
              const [dateB, hourB] = b.split('-');
              if (dateA !== dateB) return parseInt(dateA) - parseInt(dateB);
              return parseInt(hourA) - parseInt(hourB);
            })
        : [...new Set(this.chartData.map(item => String(item.acdate)))].sort((a, b) => parseInt(a) - parseInt(b));

      const isDailyDimension = this.basicInfo.dataType !== '1';
      const hasCompareSeries = this.compareEnabled && this.compareChartData && this.compareChartData.length > 0;

      const parseDateToObj = (str) => {
        if (!str) return null;
        const formatted = String(str);
        const withDash = formatted.includes('-')
          ? formatted
          : `${formatted.slice(0, 4)}-${formatted.slice(4, 6)}-${formatted.slice(6, 8)}`;
        return new Date(withDash);
      };

      const addDaysToDateStr = (dateObj, days) => {
        if (!dateObj) return null;
        const d = new Date(dateObj.getTime());
        d.setDate(d.getDate() + days);
        const y = d.getFullYear();
        const m = `${d.getMonth() + 1}`.padStart(2, '0');
        const day = `${d.getDate()}`.padStart(2, '0');
        return `${y}${m}${day}`;
      };

      const formatDisplayDate = (str) => {
        if (!str) return '';
        const s = String(str);
        const raw = s.includes('-') ? s.replace(/-/g, '') : s;
        if (raw.length !== 8) return s;
        return `${raw.slice(0, 4)}-${raw.slice(4, 6)}-${raw.slice(6, 8)}`;
      };

      const formatAxisDate = (str) => {
        if (!str) return '';
        const s = String(str);
        const raw = s.includes('-') ? s.replace(/-/g, '') : s;
        if (raw.length !== 8) return s;
        return `${raw.slice(4, 6)}-${raw.slice(6, 8)}`;
      };

      const getDayDiff = (startDateObj, target) => {
        if (!startDateObj || !target) return 0;
        const targetDate = parseDateToObj(target);
        const diffMs = targetDate.getTime() - startDateObj.getTime();
        return Math.round(diffMs / (24 * 60 * 60 * 1000));
      };

      const baseStartDateObj = (this.dateRange && this.dateRange.length === 2)
        ? parseDateToObj(this.dateRange[0])
        : null;
      const compareStartDateObj = (hasCompareSeries && this.compareDateRange && this.compareDateRange.length === 2)
        ? parseDateToObj(this.compareDateRange[0])
        : null;

      // X 轴标签：对比模式下展示当前/对比的实际日期和时间
      let xAxisLabels = dates;
      if (hasCompareSeries) {
        if (isDailyDimension && baseStartDateObj && compareStartDateObj) {
          // 天维度对比
          xAxisLabels = dates.map((_, index) => {
            const baseDateStr = addDaysToDateStr(baseStartDateObj, index);
            const compareDateStr = addDaysToDateStr(compareStartDateObj, index);
            const baseDisplay = baseDateStr ? formatAxisDate(baseDateStr) : '';
            const compareDisplay = compareDateStr ? formatAxisDate(compareDateStr) : '';
            if (baseDisplay && compareDisplay) {
              return `当前:${baseDisplay}\n对比:${compareDisplay}`;
            }
            return baseDisplay || compareDisplay || '';
          });
        } else if (!isDailyDimension) {
          // 小时维度对比
          xAxisLabels = dates.map((dateLabel, index) => {
            const [acdate, hr] = dateLabel.split('-');
            const compareItem = this.compareChartData[index];

            // 提取日期的最后两位（天）
            const day = acdate.slice(-2);

            if (compareItem) {
              const compareAcdate = String(compareItem.acdate);
              const compareDay = compareAcdate.slice(-2);
              const compareHr = String(compareItem.hr || '00').padStart(2, '0');
              return `${day} ${hr}\n${compareDay} ${compareHr}`;
            }
            return `${day} ${hr}`;
          });
        }
      }

      // 检查是否需要双Y轴
      const hasAmountMetrics = this.selectedMetrics.some(m => this.metricConfig[m].type === 'amount');
      const hasRatioMetrics = this.selectedMetrics.some(m => this.metricConfig[m].type === 'ratio');
      const needDualAxis = hasAmountMetrics && hasRatioMetrics;

      // 辅助函数：从一条记录中获取指定指标的数值
      const getMetricValue = (metric, item) => {
        if (!item) return 0;
        let value;
        if (metric === 'firstRoi') {
          const firstIncome = this.getFirstIncome(item);
          const cost = parseFloat(item.cost) || 0;
          value = cost > 0 ? parseFloat((firstIncome / cost).toFixed(2)) : 0;
        } else if (metric === 'convertCost') {
          value = this.getConvertCost(item);
        } else {
          const rawValue = item[metric];
          if (typeof rawValue === 'number') {
            value = rawValue;
          } else if (typeof rawValue === 'string') {
            value = parseFloat(rawValue) || 0;
          } else {
            value = 0;
          }
        }
        return value;
      };

      const series = [];
      this.selectedMetrics.forEach(metric => {
        const config = this.metricConfig[metric];

        // 主时间范围数据
        const mainValues = dates.map(dateLabel => {
          let item;
          if (this.basicInfo.dataType === '1') {
            // 小时维度：dateLabel 格式为 "20231201-14"
            const [acdate, hr] = dateLabel.split('-');
            const targetAcdate = parseInt(acdate);
            const targetHr = parseInt(hr);
            item = this.chartData.find(d => d.acdate === targetAcdate && (d.hr || 0) === targetHr);
          } else {
            // 天维度：dateLabel 格式为 "20231201"
            const targetAcdate = parseInt(dateLabel);
            item = this.chartData.find(d => d.acdate === targetAcdate);
          }
          return getMetricValue(metric, item);
        });
        const numericMainValues = mainValues.map(v => {
          const num = Number(v);
          return isNaN(num) ? 0 : num;
        });

        const mainSeriesName = hasCompareSeries ? `${config.name}（当前）` : config.name;
        series.push({
          name: mainSeriesName,
          type: 'line',
          yAxisIndex: needDualAxis ? config.yAxisIndex : 0,
          data: numericMainValues,
          smooth: true,
          // 增强线条样式
          lineStyle: {
            color: config.color,
            width: 5,
            shadowColor: config.color,
            shadowBlur: 3,
            shadowOffsetY: 2
          },
          // 增强数据点样式
          itemStyle: {
            color: config.color,
            borderColor: '#fff',
            borderWidth: 2,
            shadowColor: config.color,
            shadowBlur: 5
          },
          symbol: config.symbol,
          symbolSize: this.isMobile() ? 6 : 8,
          showSymbol: true,
          emphasis: {
            itemStyle: {
              borderWidth: 3,
              shadowBlur: 8
            },
            lineStyle: {
              width: 6,
              shadowBlur: 5
            }
          },
          areaStyle: this.selectedMetrics.length === 1 && !hasCompareSeries ? {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0, color: config.lightColor.replace('0.1', '0.3')
              }, {
                offset: 1, color: config.lightColor
              }]
            }
          } : null
        });

        // 对比时间范围数据
        if (hasCompareSeries) {
          const compareValues = dates.map((dateLabel, index) => {
            let item;
            if (this.basicInfo.dataType === '1') {
              // 小时维度：按索引对齐（第1小时对第1小时）
              item = this.compareChartData[index];
            } else if (compareStartDateObj) {
              // 天维度：根据偏移天数计算对比日期
              const targetAcdateStr = addDaysToDateStr(compareStartDateObj, index);
              const targetAcdate = parseInt(targetAcdateStr);
              item = this.compareChartData.find(d => d.acdate === targetAcdate);
            } else {
              // 兜底：按顺序取值
              item = this.compareChartData[index];
            }
            return getMetricValue(metric, item);
          });

          const numericCompareValues = compareValues.map(v => {
            const num = Number(v);
            return isNaN(num) ? 0 : num;
          });

          series.push({
            name: `${config.name}（对比）`,
            type: 'line',
            yAxisIndex: needDualAxis ? config.yAxisIndex : 0,
            data: numericCompareValues,
            smooth: true,
            lineStyle: {
              color: config.color,
              width: 3,
              type: 'dashed',
              shadowColor: config.color,
              shadowBlur: 2,
              shadowOffsetY: 1
            },
            itemStyle: {
              color: config.color,
              borderColor: '#fff',
              borderWidth: 1,
              shadowColor: config.color,
              shadowBlur: 3
            },
            symbol: config.symbol,
            symbolSize: this.isMobile() ? 5 : 7,
            showSymbol: true,
            emphasis: {
              itemStyle: {
                borderWidth: 3,
                shadowBlur: 6
              },
              lineStyle: {
                width: 4,
                shadowBlur: 4
              }
            }
          });
        }
      });

      // 计算Y轴数据范围
      const allValues = series.flatMap(s => s.data || []);
      const maxValue = allValues.length ? Math.max(...allValues) : 0;
      const minValue = allValues.length ? Math.min(...allValues) : 0;
      // 构建Y轴配置 - 增强视觉效果
      const yAxisConfig = needDualAxis ? [
        {
          type: 'value',
          name: '金额(元)',
          position: 'left',
          min: function(value) {
            return Math.max(0, value.min - (value.max - value.min) * 0.1);
          },
          max: function(value) {
            return value.max + (value.max - value.min) * 0.1;
          },
          nameTextStyle: {
            color: '#374151',
            fontSize: 13,
            fontWeight: '500'
          },
          axisLabel: {
            formatter: '{value}',
            color: '#6b7280',
            fontSize: 12
          },
          axisLine: {
            lineStyle: {
              color: '#d1d5db'
            }
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: '#f3f4f6',
              type: 'dashed'
            }
          }
        },
        {
          type: 'value',
          name: 'ROI',
          position: 'right',
          min: function(value) {
            return Math.max(0, value.min - (value.max - value.min) * 0.1);
          },
          max: function(value) {
            return value.max + (value.max - value.min) * 0.1;
          },
          nameTextStyle: {
            color: '#374151',
            fontSize: 13,
            fontWeight: '500'
          },
          axisLabel: {
            formatter: '{value}',
            color: '#6b7280',
            fontSize: 12
          },
          axisLine: {
            lineStyle: {
              color: '#d1d5db'
            }
          },
          splitLine: {
            show: false
          }
        }
      ] : [
        {
          type: 'value',
          name: this.getYAxisName(),
          min: function(value) {
            return Math.max(0, value.min - (value.max - value.min) * 0.1);
          },
          max: function(value) {
            return value.max + (value.max - value.min) * 0.1;
          },
          nameTextStyle: {
            color: '#374151',
            fontSize: 13,
            fontWeight: '500'
          },
          axisLabel: {
            formatter: '{value}',
            color: '#6b7280',
            fontSize: 12
          },
          axisLine: {
            lineStyle: {
              color: '#d1d5db'
            }
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: '#f3f4f6',
              type: 'dashed'
            }
          }
        }
      ];

      const option = {
        title: {
          text: this.getChartTitle(),
          left: 'center',
          textStyle: {
            fontSize: 18,
            fontWeight: 'bold',
            color: '#1f2937'
          }
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255, 255, 255, 0.98)',
          borderColor: '#e5e7eb',
          borderWidth: 1,
          padding: [12, 16],
          textStyle: {
            color: '#374151',
            fontSize: 13
          },
          extraCssText: 'box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); max-width: 400px;',
          formatter: (params) => {
            if (!params || !params.length) return '';
            const dataIndex = params[0].dataIndex;
            let headerHtml = '';

            // 小时维度对比模式下，展示详细的日期时间信息
            if (!isDailyDimension && hasCompareSeries && this.chartData && this.chartData.length > dataIndex) {
              const currentItem = this.chartData[dataIndex];
              const compareItem = this.compareChartData[dataIndex];

              const formatFullDateTime = (acdate, hr) => {
                const acdateStr = String(acdate);
                const dateStr = `${acdateStr.slice(0, 4)}-${acdateStr.slice(4, 6)}-${acdateStr.slice(6, 8)}`;
                const hourStr = String(hr || '00').padStart(2, '0');
                return `${dateStr} ${hourStr}:00`;
              };

              if (currentItem) {
                const currentDateTime = formatFullDateTime(currentItem.acdate, currentItem.hr);
                headerHtml += `<div style="color: #1f2937; font-weight: bold; margin-bottom: 4px;">📅 当前：${currentDateTime}</div>`;
              }

              if (compareItem) {
                const compareDateTime = formatFullDateTime(compareItem.acdate, compareItem.hr);
                headerHtml += `<div style="color: #6b7280; font-weight: bold; margin-bottom: 8px;">📅 对比：${compareDateTime}</div>`;
              }
            }
            // 天维度对比模式下，在标题中补充实际日期信息
            else if (isDailyDimension && hasCompareSeries && this.dateRange && this.dateRange.length === 2 && this.compareDateRange && this.compareDateRange.length === 2) {
              const baseStart = parseDateToObj(this.dateRange[0]);
              const compareStart = parseDateToObj(this.compareDateRange[0]);
              const baseDateStr = addDaysToDateStr(baseStart, dataIndex);
              const compareDateStr = addDaysToDateStr(compareStart, dataIndex);
              const formatDisplayDate = (str) => {
                if (!str) return '';
                return `${str.slice(0, 4)}-${str.slice(4, 6)}-${str.slice(6, 8)}`;
              };
              const baseDisplay = baseDateStr ? formatDisplayDate(baseDateStr) : '';
              const compareDisplay = compareDateStr ? formatDisplayDate(compareDateStr) : '';
              if (baseDisplay) {
                headerHtml += `<div style="color: #1f2937; font-weight: bold; margin-bottom: 4px;">📅 当前：${baseDisplay}</div>`;
              }
              if (compareDisplay) {
                headerHtml += `<div style="color: #6b7280; font-weight: bold; margin-bottom: 8px;">📅 对比：${compareDisplay}</div>`;
              }
            }
            // 非对比模式下的标题
            else {
              const axisText = params[0].axisValue;
              if (this.basicInfo.dataType === '1' && this.chartData && this.chartData.length > dataIndex) {
                // 小时维度非对比模式
                const currentItem = this.chartData[dataIndex];
                if (currentItem) {
                  const acdateStr = String(currentItem.acdate);
                  const dateStr = `${acdateStr.slice(0, 4)}-${acdateStr.slice(4, 6)}-${acdateStr.slice(6, 8)}`;
                  const hourStr = String(currentItem.hr || '00').padStart(2, '0');
                  headerHtml = `<div style="font-weight: bold; margin-bottom: 8px; color: #1f2937;">📅 ${dateStr} ${hourStr}:00</div>`;
                }
              } else {
                headerHtml = `<div style="font-weight: bold; margin-bottom: 8px; color: #1f2937;">${axisText}</div>`;
              }
            }

            let result = headerHtml;
            params.forEach(param => {
              const metricKey = Object.keys(this.metricConfig).find(key => param.seriesName.startsWith(this.metricConfig[key].name));
              const metricConfig = metricKey ? this.metricConfig[metricKey] : null;
              const color = param.color || (metricConfig && metricConfig.color) || '#3b82f6';
              const unit = metricConfig && metricConfig.unit ? metricConfig.unit : '';
              result += `<div style="margin: 4px 0;">
                <span style="display: inline-block; width: 12px; height: 12px; background: ${color}; border-radius: 50%; margin-right: 8px;"></span>
                <span style="font-weight: 500;">${param.seriesName}:</span>
                <span style="color: ${color}; font-weight: bold;">${param.value}${unit}</span>
              </div>`;
            });
            return result;
          }
        },
        legend: {
          show: series.length > 0,
          top: 35,
          itemGap: this.isMobile() ? 15 : 20, // 移动端减少间距
          itemWidth: this.isMobile() ? 16 : 18, // 移动端稍小的图例标记
          itemHeight: this.isMobile() ? 12 : 14,
          textStyle: {
            fontSize: this.isMobile() ? 12 : 14,
            fontWeight: '500',
            color: '#374151'
          },
          backgroundColor: 'rgba(249, 250, 251, 0.8)',
          borderColor: '#e5e7eb',
          borderWidth: 1,
          borderRadius: 6,
          padding: this.isMobile() ? [6, 12] : [8, 16],
          data: series.map(s => s.name)
        },
        grid: {
          top: series.length > 1 ? (this.isMobile() ? 90 : 80) : (this.isMobile() ? 60 : 50),
          left: needDualAxis ? (this.isMobile() ? 50 : 60) : (this.isMobile() ? 40 : 50),
          right: needDualAxis ? (this.isMobile() ? 50 : 60) : (this.isMobile() ? 20 : 30),
          bottom: this.basicInfo.dataType === '1' ? (this.isMobile() ? 90 : 80) : (this.isMobile() ? 40 : 50) // 小时维度需要更多底部空间
        },
        xAxis: {
          type: 'category',
          data: xAxisLabels,
          axisLabel: {
            formatter: (value) => {
              // 小时维度对比模式下，xAxisLabels 已经格式化好了，直接返回
              if (!isDailyDimension && hasCompareSeries) {
                return value;
              }
              // 天维度对比模式下，直接使用标签
              if (isDailyDimension && hasCompareSeries) {
                return value;
              }
              if (this.basicInfo.dataType === '1') {
                // 小时维度未对比：value格式为 "20231201-14"
                const [dateStr, hour] = value.split('-');
                return `${dateStr.slice(4, 6)}-${dateStr.slice(6, 8)}\n${hour}:00`;
              }
              // 天维度未对比：value格式为 "20231201"
              return value.slice(4, 6) + '-' + value.slice(6, 8);
            },
            color: '#6b7280',
            fontSize: this.isMobile() ? 10 : 12,
            rotate: 0, // 不旋转，使用换行显示
            interval: this.basicInfo.dataType === '1' ? 'auto' : 0, // 小时维度自动间隔显示
            margin: this.basicInfo.dataType === '1' ? 20 : 8 // 增加标签间距，确保完整显示
          },
          axisLine: {
            lineStyle: {
              color: '#d1d5db'
            }
          }
        },
        yAxis: yAxisConfig,
        series: series
      };
      this.chart.setOption(option, true); // 使用notMerge=true确保完全替换
    },

    // 获取首日回收
    getFirstIncome(row) {
      if (row.arpuData && row.arpuData.firstIncome !== undefined) {
        return row.arpuData.firstIncome;
      }
      return row.firstIncome || 0;
    },

    // 获取首日回收ROI
    getFirstIncomeRoi(row) {
      const firstIncome = this.getFirstIncome(row);
      const cost = row.cost || 0;
      return cost > 0 ? (firstIncome / cost).toFixed(2) : '0.00';
    },

    // 获取转换成本
    getConvertCost(row) {
      if (!row.convertTypes || !row.convertData) {
        return 0;
      }

      try {
        const convertData = typeof row.convertData === 'string'
          ? JSON.parse(row.convertData)
          : row.convertData;

        const convertTypes = row.convertTypes;

        // 根据转换类型确定使用哪个成本值
        if (convertTypes.includes('注册')) {
          return parseFloat(convertData.zRegisterCost) || 0;
        } else if (convertTypes.includes('激活')) {
          return parseFloat(convertData.zActivationCost) || 0;
        } else if (convertTypes.includes('付费')) {
          return parseFloat(convertData.zPayCost) || 0;
        }

        return 0;
      } catch (error) {
        return 0;
      }
    },

    // 获取图表标题
    getChartTitle() {
      if (!this.selectedMetrics || this.selectedMetrics.length === 0) {
        return '数据趋势图';
      }

      if (this.selectedMetrics.length === 1) {
        return `${this.metricConfig[this.selectedMetrics[0]].name}趋势`;
      }

      const names = this.selectedMetrics.map(metric => this.metricConfig[metric].name);
      return `${names.join('、')}对比趋势`;
    },

    // 获取Y轴名称（单轴模式）
    getYAxisName() {
      if (!this.selectedMetrics || this.selectedMetrics.length === 0) {
        return '';
      }

      const hasAmountMetrics = this.selectedMetrics.some(m => this.metricConfig[m].type === 'amount');
      const hasRatioMetrics = this.selectedMetrics.some(m => this.metricConfig[m].type === 'ratio');

      if (hasAmountMetrics && !hasRatioMetrics) {
        return '金额(元)';
      } else if (!hasAmountMetrics && hasRatioMetrics) {
        return 'ROI';
      } else {
        return '数值';
      }
    },

    // 获取图例图标
    getLegendIcon(metric) {
      const symbolMap = {
        'circle': 'circle',
        'rect': 'rect',
        'diamond': 'diamond',
        'triangle': 'triangle'
      };
      return symbolMap[this.metricConfig[metric].symbol] || 'circle';
    },

    // 检测是否为移动端
    isMobile() {
      return window.innerWidth <= 768;
    },

    // 获取利润
    getProfit(row) {
      const income = row.income || 0;
      const cashCost = row.cashCost || 0;
      return (income - cashCost).toFixed(2);
    },

    // 表格：根据索引获取对比行
    getCompareRowByIndex(index) {
      if (!this.compareEnabled || !this.compareTableData || !this.compareTableData.length) return null;

      const currentRow = this.tableData[index];
      if (!currentRow) return null;

      // 小时维度：按小时值匹配（处理数据长度不同的情况）
      if (this.basicInfo.dataType === '1') {
        // 计算查询日期范围和对比日期范围的日期差
        if (!this.dateRange || this.dateRange.length !== 2 || !this.compareDateRange || this.compareDateRange.length !== 2) {
          return null;
        }

        const currentDate = new Date(this.dateRange[0]);
        const compareDate = new Date(this.compareDateRange[0]);
        const daysDiff = Math.round((currentDate - compareDate) / (1000 * 60 * 60 * 24));

        const currentAcdate = currentRow.acdate;
        const currentHr = parseInt(currentRow.hr || 0);

        // 将 acdate 转换为 Date 对象
        const acdateStr = String(currentAcdate);
        const currentRowDate = new Date(`${acdateStr.slice(0, 4)}-${acdateStr.slice(4, 6)}-${acdateStr.slice(6, 8)}`);

        // 计算对应的对比日期（当前日期 - 日期差）
        const compareRowDate = new Date(currentRowDate.getTime() - daysDiff * 24 * 60 * 60 * 1000);
        const compareAcdate = parseInt(
          `${compareRowDate.getFullYear()}${String(compareRowDate.getMonth() + 1).padStart(2, '0')}${String(compareRowDate.getDate()).padStart(2, '0')}`
        );

        // 在对比数据中查找匹配的记录（相同日期和小时）
        const matchedRow = this.compareTableData.find(row => {
          const rowAcdate = parseInt(row.acdate);
          const rowHr = parseInt(row.hr || 0);
          return rowAcdate === compareAcdate && rowHr === currentHr;
        });

        return matchedRow || null;
      }

      // 天维度：按索引对齐（因为天数相同，长度相同）
      return this.compareTableData[index] || null;
    },

    // 表格：格式化日期（acdate 可以是 20231201 或 2023-12-01）
    formatAcdate(acdate) {
      if (!acdate) return '';
      const str = String(acdate);
      if (str.includes('-')) {
        return str;
      }
      if (str.length === 8) {
        return `${str.slice(0, 4)}-${str.slice(4, 6)}-${str.slice(6, 8)}`;
      }
      return str;
    },

    // 表格：获取对比指标值
    getCompareMetricValue(index, field) {
      const row = this.getCompareRowByIndex(index);
      if (!row) return 0;
      let value;
      if (field === 'firstIncome') {
        value = this.getFirstIncome(row);
      } else if (field === 'firstRoi') {
        value = this.getFirstIncomeRoi(row);
      } else if (field === 'convertCost') {
        value = this.getConvertCost(row);
      } else if (field === 'profit') {
        value = this.getProfit(row);
      } else {
        value = row[field];
      }
      const num = parseFloat(value);
      return isNaN(num) ? 0 : num;
    },

    // 表格：获取差异数值
    getDiffValue(base, compare) {
      const baseNum = parseFloat(base);
      const compareNum = parseFloat(compare);
      if (isNaN(baseNum) || isNaN(compareNum)) {
        return 0;
      }
      return baseNum - compareNum;
    },

    // 表格：获取差异文本（百分比）
    getDiffText(base, compare) {
      const baseNum = parseFloat(base);
      const compareNum = parseFloat(compare);
      if (isNaN(baseNum) || isNaN(compareNum)) {
        return '0%';
      }
      if (compareNum === 0) {
        return baseNum > 0 ? '+100%' : '0%';
      }
      const percentage = ((baseNum - compareNum) / compareNum) * 100;
      if (percentage === 0) return '0%';
      return percentage > 0 ? `+${percentage.toFixed(2)}%` : `${percentage.toFixed(2)}%`;
    },

    // 表格：获取差异颜色
    getDiffColor(base, compare) {
      const diff = this.getDiffValue(base, compare);
      if (diff > 0) return '#16a34a';
      if (diff < 0) return '#dc2626';
      return '#6b7280';
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;

  .page-title {
    margin: 0 0 0 15px;
    font-size: 24px;
    font-weight: bold;
    color: #303133;
  }
}

.control-card, .chart-card, .table-card {
  margin-bottom: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;

    .card-title {
      font-size: 18px;
      font-weight: bold;
      color: #303133;
      flex-shrink: 0;
    }

    .header-controls, .chart-controls {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      gap: 10px;
    }
  }
}

.info-item {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  flex-wrap: nowrap;

  label {
    font-weight: bold;
    color: #606266;
    margin-right: 8px;
    white-space: nowrap;
    flex-shrink: 0;
  }

  span {
    color: #303133;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    flex: 1;

    // 针对dict-tag组件的特殊样式
    .el-tag {
      white-space: nowrap;
      max-width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }

  // 渠道标签特殊样式
  .channel-tag {
    display: inline-block;
    white-space: nowrap;

    .el-tag {
      white-space: nowrap;
      display: inline-block;
      max-width: 100px;
      overflow: hidden;
      text-overflow: ellipsis;
      vertical-align: middle;
    }
  }
}

.chart-card {
  .chart-controls {
    .metric-selection {
      .el-checkbox-group {
        display: flex;
        flex-wrap: wrap;
        gap: 15px;

        .el-checkbox {
          margin-right: 0;

          .el-checkbox__label {
            padding-left: 8px;
            font-size: 14px;
          }
        }
      }
    }
  }
}

#trendChart {
  min-height: 400px;
}

.table-card {
  .el-table {
    .el-table__header {
      th {
        background-color: #f8f9fa;
        color: #606266;
        font-weight: bold;
      }
    }

    .el-table__body {
      tr:hover {
        background-color: #f5f7fa;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;

    .page-title {
      margin: 10px 0 0 0;
    }
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;

    .header-controls, .chart-controls {
      margin-top: 10px;
      width: 100%;
    }
  }

  .info-item {
    margin-bottom: 15px;
    flex-direction: column;
    align-items: flex-start;

    label, span {
      display: block;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      width: 100%;
    }

    span {
      margin-top: 5px;
      padding-left: 10px;
    }

    .channel-tag {
      width: 100%;

      .el-tag {
        max-width: calc(100% - 10px);
      }
    }
  }

  #trendChart {
    height: 300px;
  }

  // 移动端图表优化
  .chart-card {
    .card-header {
      .card-title {
        font-size: 16px;
      }
    }
  }
}

@media (max-width: 480px) {
  .app-container {
    padding: 10px;
  }

  .chart-controls {
    .metric-selection {
      .el-checkbox-group {
        flex-direction: column;
        gap: 8px;

        .el-checkbox {
          .el-checkbox__label {
            font-size: 12px;
          }
        }
      }
    }
  }
}
</style>
